<template>
  <a-modal
    title='操作'
    style='top: 20px;'
    :width='1200'
    v-model='visible'
    :confirmLoading='confirmLoading'
    @ok='handleSubmit'
  >
    <a-form :form='form'>
      <a-form-item style='display:none'>
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item style='display:none'>
        <a-input v-decorator="['version']" />
      </a-form-item>


      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属地区'>
            <a-select v-decorator="['tenantId', {rules: [{ required: true, message: '请选择所属地区' }]}]"
                      @change='selectTenant'
                      :disabled='tenantEnable'>
              <a-select-option v-for='item in tenantList' :key='item.id'>{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属园区'>
            <a-select v-decorator="['parkId', {rules: [{ required: true, message: '请选择所属园区' }]}]"
                      @change='selectPark'
                      :disabled='parkEnable'>
              <a-select-option v-for='item in parkList' :key='item.id'>{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属楼宇'>
            <a-select v-decorator="['buildingId', {rules: [{ required: true, message: '请选择所属楼宇' }]}]"
                      @change='selectBuilding'>
              <a-select-option v-for='item in buildingList' :key='item.id'>{{ item.buildingName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属楼层'>
            <a-select v-decorator="['buildId',{rules: [{ required: true, message: '请选择所属楼层' }]}]"
                      placeholder='所属楼层'
                      @change='selectBuildingDetail'>
              <a-select-option v-for='item in buildingDetailList' :key='item.id' :value='item.id'>
                {{ item.floorName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属房间'>
            <a-select v-decorator="['roomId',{rules: [{ required: true, message: '选择所属房间' }]}]"
                      placeholder='所属房间'
                      @change='selectRoom'>
              <a-select-option v-for='item in roomList' :key='item.id' :value='item.id'>
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='展厅面积' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='展厅面积'
                     v-decorator="['area',{rules: [{ required: true, message: '请输入展厅面积' }]}]"
                     disabled='disabled' />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='10'>
          <a-form-item label='展厅名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='展厅名称'
                     v-decorator="['meetingName',{rules: [{ required: true, message: '输入展厅名称' }]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='容纳人数' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='容纳人数'
                     v-decorator="['capacityNum',{rules: [{ required: true, message: '输入容纳人数' }]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>

        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='展厅地址 '>
            <a-input placeholder='展厅地址'
                     v-decorator="['address',{rules: [{ required: true, message: '输入展厅地址' }]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='是否启用' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-select v-decorator="['isShow',{rules: [{ required: true, message: '请选择是否启用'}]}]"
                      placeholder='是否启用'>

              <a-select-option :value='0'>
                是
              </a-select-option>
              <a-select-option :value='1'>
                否
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>

        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='负责人'>
            <a-input placeholder='负责人'
                     v-decorator="['headName',{rules: [{ required: true, message: '输入负责人' }]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='负责人联系方式' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='负责人联系方式'
                     v-decorator="['headPhone',{rules: [{ required: true, message: '输入负责人联系方式'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='启用时间'>
            <a-date-picker
              format='YYYY-MM-DD HH:mm:ss'
              valueFormat='YYYY-MM-DD HH:mm:ss'
              v-decorator="['startTime',{rules: [{ required: true, message: '输入启用时间'}]}]"
              :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              type='date'
              placeholder='选择时间'
              style='width: 100%;'

            />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='结束时间' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-date-picker
              format='YYYY-MM-DD HH:mm:ss'
              valueFormat='YYYY-MM-DD HH:mm:ss'
              v-decorator="['endDate',{rules: [{ required: true, message: '输入结束时间'}]}]"
              :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              type='date'
              placeholder='选择时间结束时间'
              style='width: 100%;'

            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='室内图片'>
            <a-upload
              v-decorator="['indoorPicUrl', {rules: [{ required: true, message: '上传室内图片' }]}]"
              list-type='picture-card'
              class='avatar-uploader'
              :file-list='fileList'
              :action='uploadUrl'
              :headers='headers'
              @preview='handlePreview'
              @change='handleChangeFileList'
            >
              <div v-if='fileList.length < 4'>
                <a-icon type='plus' />
                <div class='ant-upload-text'> 上传</div>
              </div>
            </a-upload>
            <a-modal :visible='previewVisible' :footer='null' @cancel='handleCancel'>
              <img style='width: 100%' :src='previewImage' />
            </a-modal>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script>
import { saveShowroom, get } from '@/api/admin/meeting/showroom'
import pick from 'lodash.pick'
import moment from 'moment'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getInfo } from '@/api/login'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'
import { getBuildingList } from '@/api/admin/building'
import { getBuildingDetailList } from '@/api/admin/buildingDetail'
import { getRoomListByFloorId, selectRoomById } from '@/api/admin/meeting/roomContent'

export default {
  name: 'ShowroomModal',
  props: {},
  components: {},
  mounted() {
    this.getFloorList()
  },
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      imageUrl: '',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      mdl: {},
      floorList: [],

      form: this.$form.createForm(this),
      userDetail: {},
      tenantList: [], // 地区
      parkList: [], // 园区
      buildingList: [], // 楼宇
      buildingDetailList: [], // 楼层
      roomList: [], // 房间
      tenantEnable: false,
      parkEnable: false,
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  beforeCreate() {
  },
  created() {
  },
  methods: {
    // 获取用户详细信息
    getUserDetail() {
      getInfo().then(res => {
        console.log('getUserDetail', res)
        this.userDetail = res
        // 园区：5
        if (this.userDetail.roleIds && this.userDetail.roleIds.length > 0 && this.userDetail.roleIds[0] == 5) {
          //
          // 判断：是新增就查询园区
          let { id } = this.mdl
          if (!id) {
            // 选择地区 -> 查询园区
            this.selectTenant(this.userDetail.tenantId)
            // 选择园区 -> 查询楼宇
            this.selectPark(this.userDetail.parkId)
          }
          //
          // 不可编辑
          this.tenantEnable = true
          this.parkEnable = true
          // 关联地区和园区
          this.mdl.parkId = this.userDetail.parkId
          this.mdl.tenantId = this.userDetail.tenantId
          this.form.setFieldsValue({
            parkId: this.mdl.parkId,
            tenantId: this.mdl.tenantId
          })
        }
      })
    },
    // 查询地区
    getTenantData() {
      getTenantList().then(res => {
        this.tenantList = res.rows
      })
    },
    // 选择地区 -> 查询园区
    selectTenant(id) {
      console.log('selectTenant', id)
      // 清空数据
      this.mdl.parkId = null // 园区
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间
      this.mdl.area = null // 展厅面积

      this.form.setFieldsValue({
        parkId: null, // 园区
        buildingId: null, // 楼宇
        buildId: null, // 楼层
        roomId: null, // 所属房间
        area: null // 展厅面积
      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询楼宇
    selectPark(id) {
      // 清空数据
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间
      this.mdl.area = null // 展厅面积

      this.form.setFieldsValue({
        buildingId: null, // 楼宇
        buildId: null, // 楼层
        roomId: null, // 所属房间
        area: null // 展厅面积
      })
      // 查询楼宇
      getBuildingList({
        parkId: id
      }).then(res => {
        this.buildingList = res.rows
      })
    },
    // 选择楼宇 -> 查询楼层
    selectBuilding(id) {
      // 清空数据
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间
      this.mdl.area = null // 展厅面积

      this.form.setFieldsValue({
        buildId: null, // 楼层
        roomId: null, // 所属房间
        area: null // 展厅面积
      })
      // 查询楼层
      getBuildingDetailList({
        buildingId: id
      }).then(res => {
        this.buildingDetailList = res.rows
      })
    },
    // 选择楼层 -> 查询房间
    selectBuildingDetail(buildingDetailId) {
      // 查询房间
      this.getRoomListByFloorIdMethod(buildingDetailId)
    },
    // 查询房间
    getRoomListByFloorIdMethod(buildingDetailId, id) {
      // 清空数据
      this.mdl.roomId = null // 所属房间
      this.mdl.area = null // 展厅面积

      this.form.setFieldsValue({
        roomId: null, // 所属房间
        area: null // 展厅面积
      })
      // 查询房间
      getRoomListByFloorId({
        'id': id,
        'buildingDetailId': buildingDetailId,
        'type': 0
      }).then((res) => {
        this.roomList = res.data
      })
    },
    // 选择房间 -> 查询面积
    selectRoom(id) {
      // 清空数据
      this.mdl.area = null // 展厅面积

      this.form.setFieldsValue({
        area: null // 展厅面积
      })
      // 查询面积
      selectRoomById({
        'id': id
      }).then((res) => {
        this.form.setFieldsValue({
          area: res.data.area
        })
      })
    },
    moment,
    //
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64FileList(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleCancel() {
      this.previewVisible = false
    },
    // 上传banner
    handleChangeFileList({ fileList }) {
      this.fileList = fileList
    },
    add() {
      this.form.resetFields()
      this.mdl.indoorPicUrl = null
      this.edit({ id: 0 })
    },
    edit(record) {
      this.mdl = Object.assign(record)
      let copyMdl = JSON.parse(JSON.stringify(this.mdl))
      // 查询地区
      this.getTenantData()
      //
      if (record.id) { // 编辑
        // 选择地区 -> 查询园区
        if (copyMdl.tenantId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectTenant(copyMdl.tenantId)
        }
        // 选择园区 -> 查询楼宇
        if (copyMdl.parkId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectPark(copyMdl.parkId)
        }
        // 选择楼宇 -> 查询楼层
        if (copyMdl.buildingId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectBuilding(copyMdl.buildingId)
        }
        // 选择楼层 -> 查询房间
        if (copyMdl.buildId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.getRoomListByFloorIdMethod(copyMdl.buildId, copyMdl.roomId)
          this.selectRoom(copyMdl.roomId)
        }
        // 防止替换
        this.mdl = JSON.parse(JSON.stringify(copyMdl))

      } else { // 新增

      }
      // 获取用户信息
      this.getUserDetail()
      // 图片
      if (this.mdl.indoorPicUrl) {
        this.mdl.indoorPicUrl = JSON.parse(this.mdl.indoorPicUrl)
        this.mdl.indoorPicUrl.forEach((item, i) => {
          item.url = process.env.VUE_APP_API_BASE_URL + item.url
        })
        this.fileList = this.mdl.indoorPicUrl
      } else {
        this.fileList = []
      }
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'showroomCode', 'meetingName', 'capacityNum', 'expandNum',
          'indoorPicUrl', 'address', 'startTime', 'endDate', 'isShow',
          'headName', 'headPhone', 'content', 'createBy', 'createTime',
          'updateBy', 'updateTime', 'version', 'deleteFlag',
          'tenantId', 'parkId', 'buildingId', 'buildId', 'roomId'))
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          const indoorPicUrl = []
          this.fileList.forEach((file, index) => {
            // 添加原来的
            if (file.hasOwnProperty('name') && file.hasOwnProperty('url') && file.hasOwnProperty('uid')) {
              indoorPicUrl.push({ 'name': file.name, 'url': file.name, 'uid': index })
            }
            if (file.status === 'done' && file.response.code === 0) {
              const data = file.response
              indoorPicUrl.push({ 'name': data.fileName, 'url': data.fileName, 'uid': index })
            }
          })
          // 多个图片
          values.indoorPicUrl = JSON.stringify(indoorPicUrl)
          saveShowroom(values).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
</script>
